package cn.nubia.admin.api.jinshan.service;

import cn.nubia.admin.api.jinshan.bean.CheckFileList;
import cn.nubia.admin.api.jinshan.bean.ScanResult;
import cn.nubia.admin.api.jinshan.connect.CheckRequest;
import cn.nubia.admin.common.http.JsonUtil;
import cn.nubia.admin.common.springmvc.SpringContextLoader;
import cn.nubia.admin.common.utils.Jackson2Util;
import cn.nubia.admin.common.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 金山检测口
 * Created by wangj on 2015/7/23.
 */
@Service
public class CheckService {
    private final static Logger logger = LoggerFactory.getLogger(CheckService.class);

    private final static ExecutorService executorService = Executors.newSingleThreadExecutor();
    /**
     * 检测接口,创建方法
     * CheckFileList checkFileList = new CheckFileList();
     * checkFileList.addScanFile(String url , String md5 , String fileId).addScanFile(String url , String md5 , String fileId);
     */
    public void check(final CheckFileList checkFileList) {
        if (checkFileList == null) {
            logger.error("待检测文件列表为空");
            return;
        }
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                CheckRequest checkRequest = SpringContextLoader.getBean(CheckRequest.class);
                checkRequest.setCheckFiles(checkFileList);
                checkRequest.sendRequest();
            }
        });
    }

    /**
     * 校验结果返回
     * @param scanResultStr
     */
    public void callback(String scanResultStr) {
        try {
            ScanResult scanResult = Jackson2Util.toObject(scanResultStr, ScanResult.class);
            //TODO
        }catch (Exception e) {
            logger.error("处理返回结果出错,原始串:{}" ,scanResultStr , e);
        }
    }



    @PreDestroy
    public void shutdown() {
        if (logger.isInfoEnabled()) {
            logger.info("shutdown check service!");
        }
        executorService.shutdown();
    }

    /**
     * 校验md5码
     * @param tpl
     * @param sign
     * @param version
     * @param scanResult
     * @return
     */
    public boolean checkParams(Integer tpl, String sign, String version, String scanResult) {
        String md5Sign = buildSign(tpl,version,scanResult);
        if (md5Sign.equals(sign)){
            return true;
        }
        return false;
    }

    /**
     *
     * 签名算法:
     step1: 将所有输入参数（包括GET 和POST 参数，但除sign 参数外）格式化为"key=value"格式，
     如"k1=v1"、"k2=v2"、"k3=v3"；
     step2: 将格式化好的参数键值对以字典序升序方式排列后，拼接在一起，如"k1=v1k2=v2k3=v3"；
     step3: 在拼接好的字符串末尾拼接上我们为金山提供的secure_key，并对获取到的字符串算MD5
     签名，签名值即为sign 参数的值。
     * @param tpl
     * @param version
     * @param scanResult
     * @return
     */
    private String buildSign(Integer tpl, String version, String scanResult) {
        CheckRequest checkRequest = SpringContextLoader.getBean(CheckRequest.class);
        StringBuilder sb = new StringBuilder();
        sb.append("v=").append(version).append("tpl=").append(tpl).append("scanResult=" ).append(scanResult).append("secure_key").append(checkRequest.getSecureKey());
        return MD5Util.md5(sb.toString());
    }

    public static void main(String[] args) {

    }
}
